<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ChangeCode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = "change:code  
                         {--Y|year=}
                         {--L|length=}";

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "change the length of the vuls's code";

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $year = $this->option('year');
        $length = $this->option('length') ? $this->option('length'):4;
        if($year){
            $confirm="you input the year is ".$year.", and the length is ".$length." ? [y|N]";
        }else{
            $confirm="the length is ".$length." ? [y|N]";
        }
        if ($this->confirm($confirm)) {
            if($year)
            {
                $sql = "select * from vuls where date_format(created_at,'%Y')=:mytime";
                $vuls = DB::select($sql,['mytime' => $year]);
            }else{
                $vuls = DB::table('vuls')->get();
            }

            foreach ($vuls as $value)
            {
                $update=[];
                $original=$value-> vuls_number;
                $number=explode("-", $value-> vuls_number);
                $count=intval($number[2]);
                $num = str_pad($count, $length, 0, STR_PAD_LEFT);
                $number[2]=$num;
                $vulscode=implode("-", $number);
                $update=["vuls_number"=>$vulscode];
                $result1 = DB::table('vuls')
                    ->where('id', $value->id)
                    ->update($update);
                if($result1)
                {
                    $this->info($original."->".$vulscode." success");
                }else{
                    $this->error($original."->".$vulscode." fail");
                }
            }

        }
    }
    private function  selectYear($year)
    {
        $result=strpos($year,"0",0);
        if($result)
        {
            $result=$result+1;
        }
        $years=substr($year,$result);
        return $years;
    }
}
